// index.ts

import HeroHelper from "../../helpers/heroHelper";

import heroesData from "../../data/heros";
import { randomNum } from "../../utils/util";

import { EPosition } from "../../typings/types/hero";

// 所有英雄 按位置分类
const ALL_HEROS: any = {
  [EPosition.TOP]: [],
  [EPosition.AP]: [],
  [EPosition.JUG]: [],
  [EPosition.AD]: [],
  [EPosition.SUP]: [],
};

Page({
  data: {
    teams: [
      {
        name: "蓝色方",
        color: "blue",
      },
      {
        name: "红色方",
        color: "red",
      },
    ],

    pickHeroList: [],
    hero: {},
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: "../logs/logs",
    });
  },

  // 随机pick英雄
  randomHeroTap() {
    let pickHeroList: any = [];
    // 遍历位置
    for (var key in EPosition) {
      //@ts-ignore
      const value = EPosition[key];
      // 调用选择英雄函数
      const list = this.pickAndUniqueHeros(pickHeroList, ALL_HEROS[value]);
      pickHeroList.push(...list);
    }
    this.setData({
      pickHeroList,
    });
  },

  // 英雄随机选择 & pick去重
  pickAndUniqueHeros(pickHeroList: any, allHeroList: any[]) {
    // 随机选择
    //@ts-ignore
    const heroList: any = randomNum(1, allHeroList.length, 2, allHeroList);
    // 去重
    while (
      pickHeroList.includes(heroList[0]) ||
      pickHeroList.includes(heroList[1])
    ) {
      this.pickAndUniqueHeros(pickHeroList, allHeroList);
    }
    return heroList;
  },

  onLoad() {
    this.getAllHeroList();
    this.randomHeroTap();
  },

  // 获取所有英雄
  getAllHeroList() {
    heroesData.forEach((item) => {
      const hero = new HeroHelper({
        id: item.ename,
        name: item.cname,
        avatar: `${item.ename}`,
        heroType: item.hero_type,
        heroType2: item.hero_type2,
        heroPos: item.hero_pos,
        heroPos2: item.hero_pos2,
      });
      this.sortHero(hero);
    });
    console.log(ALL_HEROS);
  },

  // 英雄位置分类
  sortHero(hero: any) {
    const { positions = [] } = hero;

    for (var key in EPosition) {
      //@ts-ignore
      const value = EPosition[key];
      // 如果包含位置
      if (positions.includes(value)) {
        ALL_HEROS[value].push(hero);
      }
    }
  },

  getPosition(positions: any) {
    const result = randomNum(1, positions.length, 1, positions);
    return result;
  },
});
